package com.lagou.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.lagou.bean.UpLoadResult;
import com.lagou.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileUpLoadService {

    private static int MAX_FILE_SIZE_OF_MB = 5;

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;

    /**
     * 允许上传的格式
     */
    private static final String[] IMAGE_TYPE = new String[]{".jpg", ".jpeg", ".png"};

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    public UpLoadResult upload(MultipartFile multipartFile) {

        UpLoadResult upLoadResult = new UpLoadResult();

        String originalFilename = multipartFile.getOriginalFilename();

        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(originalFilename, type)) {
                isLegal = true;
                break;
            }
        }

        if (!isLegal) {
            System.out.println("不支持的文件类型:[" + originalFilename + "]");
            upLoadResult.setStatus("error");
            return upLoadResult;
        }

        if (!isAllowed(multipartFile, MAX_FILE_SIZE_OF_MB)) {
            System.out.println("文件过大:[" + originalFilename + "]，不得超过" + MAX_FILE_SIZE_OF_MB + "MB");
            upLoadResult.setStatus("error");
            return upLoadResult;
        }

        String filePath = getFilePath(originalFilename);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            System.out.println("上传过程中发生意外错误，上传失败！");
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return upLoadResult;
        }

        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
        upLoadResult.setUid(filePath);

        System.out.println("文件上传成功!");
        return upLoadResult;
    }

    /**
     * 根据对象名下载文件
     */
    public String download(String objectName) {
        System.out.println("获取到下载请求对象名：" + objectName);

        String localFileName = StringUtils.substringAfterLast(objectName, "/");
        String filePath = "F:\\temp\\oss\\" + localFileName;

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(aliyunConfig.getBucketName(), objectName),
                new File(filePath));

        return filePath;
    }

    /**
     * 根据对象名删除文件
     *
     * @param objectName
     */
    public void delete(String objectName) {
        System.out.println("获取到删除请求对象名：" + objectName);

        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(aliyunConfig.getBucketName(), objectName);
    }

    /**
     * 生成不重复的文件路径和文件名
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

    /**
     * 判定文件大小是否被允许
     */
    public static boolean isAllowed(MultipartFile file, int maxSizeOfMb) {
        long length = file.getSize();
        double fileSizeOfMb = (double) length / 1048576;

        return fileSizeOfMb <= maxSizeOfMb;
    }
}
